package com.gmom.tako.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import com.gmom.tako.AsyncTaskProgress;
import com.gmom.tako.MainActivity;
import com.gmom.tako.R;
import com.gmom.tako.RssReaderTask;
import com.gmom.tako.RssUrlAdditionTask;
import com.gmom.tako.db.DbAccessor;
import com.gmom.tako.model.Rss;
import com.gmom.tako.model.Url;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class TakoService extends IntentService implements AsyncTaskProgress{

	public TakoService() {
		super("takos-service");
		// TODO Auto-generated constructor stub
	}
	private ITakoService.Stub binder = new ITakoService.Stub() {
		@Override
		public void checkRss() throws RemoteException {
			Toast.makeText(getApplicationContext(), "RSS　更新しました", Toast.LENGTH_LONG).show();
		}
	};
	@Override
	public IBinder onBind(Intent arg0) {
		return binder;
	}
	
	@Override
	public int onStartCommand(Intent in,int flag,int startId) {
		int i = super.onStartCommand(in, flag, startId);
		Toast.makeText(this, "startservice", Toast.LENGTH_SHORT).show();
		return i;
	}
	public void onDestroy(){
		Toast.makeText(this, "stopservice", Toast.LENGTH_SHORT).show();
	}
	@Override
	protected void onHandleIntent(Intent intent) {
		while (true) {
			try {
				DbAccessor dba = new DbAccessor();
				List<Url> urls = dba.getUrlList(getApplicationContext());
				Url[] url_arr = urls.toArray(new Url[0]);
				new RssReaderTask(this,getApplicationContext()).execute(url_arr);
				showNotification();
				Thread.sleep(1000*60*60*24);
			} catch (InterruptedException e) {
			}
		}
	}
	
	private void showNotification(){
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notification = new Notification(
				R.drawable.icon_robot,
				"RSS更新しました",
				System.currentTimeMillis());
		Intent intent = new Intent(this,MainActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
		notification.setLatestEventInfo(getApplicationContext(),"TakosReader","RSS更新しました!",contentIntent);
		notification.icon = R.drawable.icon_robot;
		nm.notify(R.string.app_name, notification);
	}

	@Override
	public void onComplete(List<Rss> rss) {
		// TODO Auto-generated method stub
		
	}
}
